package com.twxm.breed.service;

import com.twxm.breed.entity.CategoryInfo;
import com.twxm.breed.entity.DeviceInfo;
import com.twxm.breed.iot.ALiYunIOTAPI;
import com.twxm.breed.mapper.CategoryInfoMapper;
import com.twxm.breed.mapper.DeviceInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DeviceCateInfoService {
    @Autowired
    private DeviceInfoMapper deviceInfoMapper;
    @Autowired
    private CategoryInfoMapper categoryInfoMapper;
    @Transactional(rollbackFor = Exception.class)
    public void insertDevice(CategoryInfo categoryInfo, DeviceInfo deviceInfo) throws Exception{
        //如果产品不存在，那么就创建产品
        String productKey = categoryInfoMapper.getProductKey(categoryInfo);
        if (productKey == null || productKey.equals("")){
            String newProductKey = ALiYunIOTAPI.getInstance().createProduct(categoryInfo.getModel());
            categoryInfo.setProductKey(newProductKey);
            categoryInfoMapper.insertCategory(categoryInfo);
            Integer cateId = categoryInfoMapper.getId(categoryInfo);
            categoryInfo.setCategoryId(cateId);
        }else{
            categoryInfo.setProductKey(productKey);
            Integer cateId = categoryInfoMapper.getId(categoryInfo);
            categoryInfo.setCategoryId(cateId);
        }

        //创建设备
        if (ALiYunIOTAPI.getInstance().importDevice(categoryInfo.getProductKey(),deviceInfo.getDeviceId())){
            deviceInfo.setStatus(0);
            deviceInfo.setCategoryInfo(categoryInfo);
            deviceInfoMapper.insertDevice(deviceInfo);
        }
    }
}
